<template>
  <div>
    <Breadcrumb></Breadcrumb>
    <PageDetailLayout @formCancel="commandFormCancel" @formSubmit="commandFormSubmit">
      <el-form v-loading="commandFormLoading" :ref="commandFormRef" :model="commandForm" :rules="commandFormRules"
               size="small" label-width="150px">
        <el-form-item label="命令协议">
          <el-input disabled v-model="protocolInfo.protocolName"></el-input>
        </el-form-item>
        <el-form-item label="命令名称">
          <el-input disabled v-model="commandForm.commandName"></el-input>
        </el-form-item>
        <!-- v-if="genCommInfo.generalCommandType !== 5" -->
        <el-form-item label="关联通用命令">
          <el-select v-model="commandForm.generalCommand" clearable filterable class="width-100"
                     placeholder="请选择通用命令"
                     @change="genCommChanged">
            <el-option-group v-for="(group, idx) in genCommData" :key="idx" :label="group.label">
              <el-option v-for="(item, idx) in group.options" :key="idx"
                         :label="`${item.methodName} ${item.methodAlias || ''}`" :value="item._id">
                <span>{{item.methodName}}</span>
                <span class="mar-lft font-color-warning">{{item.methodAlias || ''}}</span>
              </el-option>
            </el-option-group>
          </el-select>
        </el-form-item>

        <el-form-item label="命令方向" prop="commandOrientation">
          <el-radio-group v-model="commandForm.commandOrientation">
            <el-radio :label="orientation.value" :key="idx"
                      v-for="(orientation, idx) in commonConfig.commandOrientation">{{orientation.label}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否无返回">
          <el-radio-group v-model="commandForm.noResponse">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <!--modbus 相关-->
        <div style="padding-left: 75px">
          <el-collapse class="mar-top mar-btm" v-if="judgeProtocolType('MODBUS')">
            <el-collapse-item name="modbus-setting">
              <template slot="title">
                <div class="el-form-item__label font-color-warning font-weight-bold"><span>MODBUS 相关设置</span></div>
              </template>
              <el-form-item label="方法编码">
                <el-select v-model="commandForm.commandSpecial.funcCode" clearable filterable class="width-100"
                           placeholder="请选择方法编码" @change="funcCodeChanged">
                  <el-option :label="`${func.label} ${func.value}`" :value="func.value" :key="idx"
                             v-for="(func, idx) in commonConfig.modbusFuncCode"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="寄存器读取数量">
                <el-input-number class="width-50" v-model="commandForm.commandSpecial.nOfRegisters"  @change="funcCodeChanged"
                                 :min="0"></el-input-number>
              </el-form-item>
              <el-form-item label="开始位类型">
                <el-radio-group v-model="commandForm.commandSpecial.isStartFunc" @change="funcCodeChanged">
                  <el-radio :label="type.value" :key="idx" v-for="(type, idx) in commonConfig.modebusStartAddrType">
                    {{type.label}}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="!commandForm.commandSpecial.isStartFunc" label="开始位">
                <el-input-number class="width-50" v-model="commandForm.commandSpecial.startingAddress" @change="funcCodeChanged"
                                 :min="0"></el-input-number>
              </el-form-item>
              <el-form-item v-else label="开始位方法">
                <el-select v-model="commandForm.commandSpecial.startFunc" clearable filterable class="width-100"
                           placeholder="开始位方法" @change="funcCodeChanged">
                  <el-option label="无" value=""></el-option>
                  <el-option :label="func.label" :value="func.value" :key="idx"
                             v-for="(func, idx) in analyzeFuncData"></el-option>
                </el-select>
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
        </div>

        <!-- KNX 相关 -->
        <div style="padding-left: 75px">
          <el-collapse class="mar-top mar-btm" v-if="judgeProtocolType('KNX')">
            <el-collapse-item name="modbus-setting">
              <template slot="title">
                <div class="el-form-item__label font-color-warning font-weight-bold"><span>KNX 相关设置</span></div>
              </template>
              <el-form-item label="方法编码">
                <el-select v-model="commandForm.commandSpecial.funcCode" clearable filterable class="width-100"
                           placeholder="请选择方法编码">
                  <el-option :label="`${func.label} ${func.value}`" :value="func.value" :key="idx"
                             v-for="(func, idx) in commonConfig.knxFuncCode"></el-option>
                </el-select>
              </el-form-item>
            </el-collapse-item>
          </el-collapse>
        </div>

        <!--http 相关-->
        <div style="padding-left: 75px">
          <el-collapse  v-model="activeHttp" class="mar-top mar-btm" v-if="judgeProtocolType('HTTP') || judgeProtocolType('COAP')">
            <el-collapse-item name="http-setting">
              <template slot="title">
                <div class="el-form-item__label font-color-warning font-weight-bold"><span>HTTP 相关设置</span></div>
              </template>
              <HttpSetting :gen-comm-info="genCommInfo" :base-setting="commandForm.commandSpecial"
                           :http-url-info="httpUrlInfo" :http-headers="httpHeaders" :http-content="httpContent"
                           :http-response="httpResponse" :http-content-info="httpContentInfo"
                           :http-response-info="httpResponseInfo" :encodeFunc="commandForm.encodeFunc"
                           :decodeFunc="commandForm.decodeFunc" @clickHttpParamTag="clickCommandTag"
                           :authenticationConfig="authenticationConfig"></HttpSetting>
            </el-collapse-item>
          </el-collapse>
        </div>
        <!--MQTT 相关-->
        <div style="padding-left: 75px">
          <el-collapse  v-model="activeMqtt"  class="mar-top mar-btm" v-if="judgeProtocolType('MQTT')">
            <el-collapse-item name="mqtt-setting">
              <template slot="title">
                <div class="el-form-item__label font-color-warning font-weight-bold"><span>MQTT 相关设置</span></div>
              </template>
              <MqttSetting :gen-comm-info="genCommInfo" :base-setting="commandForm.commandSpecial"
                           :mqtt-pub-topic-info="mqttPubTopicInfo" :mqtt-sub-topic-info="mqttSubTopicInfo"
                           :mqtt-response="mqttResponse"  :mqtt-response-info="mqttResponseInfo" :mqtt-payload="mqttPayload"
                           :mqtt-payload-info="mqttPayloadInfo" @clickHttpParamTag="clickCommandTag"></MqttSetting>

            </el-collapse-item>
          </el-collapse>
        </div>
        <div v-if="!judgeProtocolType('HTTP')  && !judgeProtocolType('MQTT')">
        <el-form-item
            :label="commandForm.commandOrientation === commonConfig.commandOrientation[0].value ? '设备请求码流模板' : '控制码流模板'">
            <CommandStreamTag :validate="true" :validate-type="commonConfig.analyzeFuncType[0].value"
                              :gen-comm-info="genCommInfo" :stream-str-info="reqStreamInfo" :stream-tags="reqTagData"
                              :encodeFunc="commandForm.encodeFunc" :decodeFunc="commandForm.decodeFunc"
                              @clickCommandTag="clickCommandTag"></CommandStreamTag>
          </el-form-item>
          <el-form-item label="码流模板示例">
            <el-input v-model="reqExample" placeholder="请填写码流模板示例"></el-input>
          </el-form-item>
          <el-form-item
            :label="commandForm.commandOrientation === commonConfig.commandOrientation[0].value ? '分控响应码流模板' : '响应码流模板'">
            <CommandStreamTag :validate="true" :validate-type="commonConfig.analyzeFuncType[1].value"
                              :gen-comm-info="genCommInfo" :stream-str-info="rspStreamInfo" :stream-tags="rspTagData"
                              :encodeFunc="commandForm.encodeFunc" :decodeFunc="commandForm.decodeFunc"
                              @clickCommandTag="clickCommandTag"></CommandStreamTag>
          </el-form-item>
          <el-form-item label="码流模板示例">
            <el-input v-model="rspExample" placeholder="请填写码流模板示例"></el-input>
          </el-form-item>
        </div>

        <el-row>
          <el-col :span="8">
            <el-form-item label="编码函数设置">
              <el-select v-model="commandForm.encodeFunc" clearable filterable class="width-100"
                         placeholder="请选择编码函数">
                <el-option label="无" value=""></el-option>
                <el-option :label="func.label" :value="func.value" :key="idx"
                           v-for="(func, idx) in analyzeFuncData"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="解码函数设置">
              <el-select v-model="commandForm.decodeFunc" clearable filterable class="width-100"
                         placeholder="请选择解码函数">
                <el-option label="无" value=""></el-option>
                <el-option :label="func.label" :value="func.value" :key="idx"
                           v-for="(func, idx) in analyzeFuncData"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="参数处理函数">
              <el-select v-model="commandForm.paramProcessFunc" clearable filterable class="width-100"
                         placeholder="请选择参数处理函数">
                <el-option label="无" value=""></el-option>
                <el-option :label="func.label" :value="func.value" :key="idx"
                           v-for="(func, idx) in analyzeFuncData"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="关联假反馈响应命令" v-if="commandType!==2">
          <el-select v-model="commandForm.relFalseFeedbackRsp " clearable filterable class="width-100"
                     placeholder="请选择假反馈响应命令">
            <el-option v-for="(item, idx) in relFalseFeedbackRspList" :key="idx"
                       :label="item.commandName" :value="item._id">
            </el-option>

          </el-select>
        </el-form-item>
        <!--关联命令相关-->
        <el-form-item label="关联命令">
          <RelatedCommand :related-commands="relatedCommands" :rel-comm-sel-data="relCommSelFilterData"></RelatedCommand>
        </el-form-item>
        <!--联合 storeKey 相关-->
        <el-form-item label="联合storeKey">
          <CombinedStoreKey :combined-store-keys="combinedStoreKeys" :gen-comm-info="genCommInfo"></CombinedStoreKey>
        </el-form-item>

        <el-form-item label="最小控制间隔(ms)">
          <el-input-number class="width-50" v-model="commandForm.minCtrInterval" :min="0" :step="100"></el-input-number>
        </el-form-item>
        <el-form-item label="等待时长(ms)">
          <el-input-number class="width-50"
                           v-model="commandForm.waitingTime" :min="0" :step="100"></el-input-number>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="commandForm.remarks" placeholder="请填写备注"></el-input>
        </el-form-item>
      </el-form>
      <!--command map 相关-->
      <DeviceCommandMap :command-map-info="selectedCommMap" :isEditor="true" :storeKeyData="[]"></DeviceCommandMap>
    </PageDetailLayout>
  </div>
</template>

<script>
  import {commonConfig} from "@/config/common";
  import {commonString, msgCode} from "@/config/string";
  import {routerMeta} from "@/router/routerMeta";
  import {messageHandle, deepCopyWithJson, dealWithModelProtocol, hasAnyEmptyProperty} from "@/utils";
  import EnumDynamic from "../../../components/EnumDynamic";
  import DeviceCommandMap from "./partial/DeviceCommandMap";
  import CommandStreamTag from "../../../components/CommandStreamTag";
  import HttpSetting from "./partial/HttpSetting";
  import RelatedCommand from "./partial/RelatedCommand";
  import CombinedStoreKey from "./partial/CombinedStoreKey";
  import MqttSetting from "@/page/device/command/partial/MqttSetting.vue";

  export default {
    name: "DeviceCommandEdit",
    components: {
      MqttSetting,
      EnumDynamic, DeviceCommandMap, CommandStreamTag,
      HttpSetting, RelatedCommand, CombinedStoreKey
    },
    data() {
      return {
        commonConfig: commonConfig,
        protocolId: '',
        protocolInfo: {},
        commandId: '',
        genCommData: [],
        genCommInfo: {}, // 当前选择的 genComm
        analyzeFuncData: [],
        relCommSelData: [], // 关联命令数据源
        commandFormLoading: false,
        commandForm: {},
        commandFormRules: {
          commandOrientation: [
            {required: true, message: '请选择命令方向', trigger: 'blur'}
          ],
        },
        commandFormRef: 'commandFormRef',
        isEditCommand: false,

        // 码流模板相关
        rspStreamInfo: {
          identify: 'Rsp',
          value: '',
          placeholder: '响应码流模板'
        },
        reqStreamInfo: {
          identify: 'Req',
          value: '',
          placeholder: '控制码流模板'
        },
        reqTagData: [],
        rspTagData: [],
        reqExample: '',
        rspExample: '',
        // http 相关
        httpUrlInfo: {},
        httpHeaders: [],
        httpContent: [],
        httpResponse: [],
        activeHttp: 'http-setting',
        // http text/html 相关
        httpContentInfo: {},
        httpResponseInfo: {},
        //mqtt相关
        activeMqtt:'mqtt-setting',
        mqttPubTopicInfo: {},//发布话题
        mqttSubTopicInfo: {},//订阅话题
        mqttPayload:[],
        mqttPayloadInfo: {},//发布类型
        mqttResponse: [],
        mqttResponseInfo: {},//订阅类型
        //鉴权配置相关
        authenticationConfig: {},
        // 关联命令相关
        relatedCommands: [],
        // 联合 storeKey 相关
        combinedStoreKeys: [],

        // command map 相关
        selectedCommMap: {
          show: false,
          type: 'Req',
          tag: {},
          genCommInfo: {}
        },
        commonSearch: [],
        commandType: ''
      }
    },
    activated() {
      this.protocolId = this.$route.params.pid;
      this.commandId = this.$route.params.cid;
      this.initCommandForm();
      this.getAnalyzeFuncData();
      this.getProtocolInfo();
      this.getCommandInfo();
      this.getSearchInfo()
    },
    computed: {
      relFalseFeedbackRspList: function () {
        return this.commonSearch.filter((item) => {
          // 协议下的命令的命令类型为通用查询2
          return item.commandType == 2
        })
      },
      relCommSelFilterData: function () {
        let filterData=[]
        //关联命令数据源
        filterData=  this.relCommSelData.filter(f => f.commandName!==this.commandForm.commandName)
        // 将通用命令根据命令类型分组
        const initRelCommData = deepCopyWithJson(commonConfig.commandType).map(ct => {
          return {...ct, options: []};
        });
        filterData.forEach(d => {
          const relComm = initRelCommData.find(f => {
            return f.value === d.commandType;
          });
          relComm && (relComm.options.push(d));
        });
        initRelCommData.forEach(gc => {
          const {options = []} = gc;
          options.length && (filterData.push(gc));
        });
        return filterData
      }
    },
    methods: {
      initCommandForm() {
        this.commandForm = {
          generalCommand: '',
          commandName: '',
          commandType: '',
          commandOrientation: 1,
          analyzeWay: 1,
          noResponse: 0,
          encodeFunc: '',
          decodeFunc: '',
          paramProcessFunc: '',
          commandSpecial: {
            // modbus 相关设置
            funcCode: '',
            startingAddress: 0,
            nOfRegisters: 0,
            isStartFunc: false,
            startFunc: '',
            // http 相关设置
            httpMethod: commonConfig.httpMethod[0].value,
            httpContentType: commonConfig.httpContentType[0].value,
            httpContentStr: '',
            httpResponseStr: '',
            //mqtt设置
            mqttPubQos: 1,//发布qos
            mqttSubQos: 1,//订阅qos
            mqttPayloadType:commonConfig.mqttContentType[0].value,
            mqttResponseType:commonConfig.mqttContentType[0].value,
          },
          minCtrInterval: 1000,
          waitingTime: 5000,
          remarks: '',
        };

        // 码流解析相关数据源
        this.reqTagData = [];
        this.rspTagData = [];

        // http 相关数据源
        this.httpUrlInfo = {
          httpUrlStr: {
            identify: 'Url',
            value: '',
            size: 'medium',
            placeholder: ''
          },
          httpUrlTagData: [],
        };
        // mqttSub 相关数据源
        this.mqttPubTopicInfo = {
          mqttPubTopicStr: {
            identify: 'Url',
            value: '',
            size: 'medium',
            placeholder: '发布topic'
          },
          mqttPubTopicTagData: [],
        };
        this.mqttSubTopicInfo = {
          mqttSubTopicStr: {
            identify: 'Url',
            value: '',
            size: 'medium',
            placeholder: '订阅topic'
          },
          mqttSubTopicTagData: [],
        };
        this.mqttPayloadInfo = {
          mqttPayloadStr: {
            identify: 'Url',
            value: '',
            size: 'medium',
            placeholder: 'mqttPayload'
          },
          mqttPayloadTagData: [],
        };
        this.mqttResponseInfo = {
          mqttResponseStr: {
            identify: 'Url',
            value: '',
            size: 'medium',
            placeholder: 'mqttResponse'
          },
          mqttResponseData: [],
        };
        this.mqttPayload=[]
        this.mqttResponse=[]
        this.httpHeaders = [];
        // http application/json 相关
        this.httpContent = [];
        this.httpResponse = [];
        // http text/html 相关
        this.httpContentInfo = {
          httpContentStr: {
            identify: 'Content',
            value: '',
            size: 'medium',
            placeholder: 'xml'
          },
          httpContentTagData: [],
        };
        this.httpResponseInfo = {
          httpResponseStr: {
            identify: 'Rsp',
            value: '',
            size: 'medium',
            placeholder: 'response xml'
          },
          httpResponseTagData: [],
        };
        this.authenticationConfig={
          checkFunc:'',
          authFunc:''
        }
        // 关联命令相关
        this.relatedCommands = [];
        // 联合 storeKey 相关
        this.combinedStoreKeys = [];

      },
      //查找设备协议的通用查询命令
      getSearchInfo() {
        const selector = {protocol: this.protocolId};
        const params = {
          pageNo: 1,
          pageSize: 1000,
          filters: [],
          sort: []
        }
        API.command.commandList({selector, ...params}).then(result => {

          const {data = []} = result;
          this.commonSearch = data;

        }).catch(err => {
          console.log('err', err)
        });
      },
      resetCommandForm() {
        this.initCommandForm();
        const commandForm = this.$refs[this.commandFormRef];
        commandForm && commandForm.resetFields();
      },
      judgeProtocolType(type = '') {
        return this.protocolInfo.protocolType && this.protocolInfo.protocolType.includes(type);
      },
      getAnalyzeFuncData() {
        API.analyzeFunc.analyzeFuncAll().then(result => {
          const {data = []} = result;
          this.analyzeFuncData = data;
        }).catch(err => {
          console.log('err', err)
        });
      },
      getProtocolInfo() {
        this.commandFormLoading = true;
        const param = {_id: this.protocolId};
        API.protocol.protocolDetail(param).then(result => {
          const {data = {}} = result;
          this.protocolInfo = data;
          this.getGenCommData();
          this.getRelCommData();
        }).catch(err => {
          console.log('err', err)
          this.commandFormLoading = false;
        });
      },
      getRelCommData() {
        const param = {protocol: this.protocolInfo._id};
        API.command.commandAll(param).then(result => {
          const {data = []} = result;
          this.relCommSelData = data;
        }).catch(err => {
          console.log('err', err)
        });
      },

      getGenCommData() {
        const param = {deviceType: this.protocolInfo.deviceType};
        API.genCommand.genCommAll(param).then(result => {
          const {data = []} = result;
          this.commandFormLoading = false;
          this.genCommData = [];
          // 将通用命令根据命令类型分组
          const initGenCommData = deepCopyWithJson(commonConfig.commandType).map(ct => {
            return {...ct, options: []};
          });
          data.forEach(d => {
            const genComm = initGenCommData.find(f => {
              return f.value === d.generalCommandType;
            });
            genComm && (genComm.options.push(d));
          });
          initGenCommData.forEach(gc => {
            const {options = []} = gc;
            options.length && (this.genCommData.push(gc));
          });
          this.genCommChanged(this.commandForm.generalCommand);
        }).catch(err => {
          console.log('err', err)
          this.commandFormLoading = false;
        });
      },
      getCommandInfo() {
        this.commandFormLoading = true;
        const param = {_id: this.commandId};
        API.command.commandDetail(param).then(result => {
          this.commandFormLoading = false;
          const {data = {}} = result;
          this.commandForm = data;
          this.commandType = data.commandType
          this.genCommChanged(this.commandForm.generalCommand);
          const {
            commandSpecial, reqStreamStr = '', rspStreamStr = '',
            reqExample = '', rspExample = '', reqStream = [],
            rspStream = [], relatedCommands = [], combinedStoreKeys = []
          } = this.commandForm;
          if (commandSpecial) {
            const {
              httpUrl = '', httpUrlParams = [],
              httpContent = [], httpResponse = [],
              httpContentStr = '', httpContentParams = [],
              httpResponseStr = '', httpResponseParams = [],
              httpHeaders = [], authenticationConfig = {},
              mqttPubTopic = '', mqttSubTopic = '',
              mqttPubTopicParams = [], mqttSubTopicParams = [],
              mqttPubQos=1, mqttSubQos=1,
              mqttPayload=[], mqttResponse=[],mqttPayloadStr='',mqttResponseStr='',
              mqttPayloadParams=[], mqttResponseParams=[]

            } = commandSpecial;
            console.log('commandSpecial', mqttPubTopic);
           // 根据后台返回数据组装前台页面需要的结构
            const getStreamInfo = (src = [], identify) => {
              return src.map(s => {
                return {
                  key: s.key,
                  value: {
                    valueStreamInfo: {
                      identify: identify,
                      value: s.valueStr,
                      size: 'medium',
                      placeholder: ''
                    },
                    valueTagData: s.valueParams || [],
                  }
                }
              }) || [];
            };
            this.httpUrlInfo = {
              httpUrlStr: {
                identify: 'Url',
                value: httpUrl,
                size: 'medium',
                placeholder: ''
              },
              httpUrlTagData: httpUrlParams,
            };
            this.httpHeaders = getStreamInfo(httpHeaders, 'Header');
            // http application/json 相关
            this.httpContent = getStreamInfo(httpContent, 'content');
            this.httpResponse = getStreamInfo(httpResponse, 'Rsp');
            // http text/html 相关
            this.httpContentInfo = {
              httpContentStr: {
                identify: 'Content',
                value: httpContentStr,
                size: 'medium',
                placeholder: 'xml'
              },
              httpContentTagData: httpContentParams,
            };
            this.httpResponseInfo = {
              httpResponseStr: {
                identify: 'Rsp',
                value: httpResponseStr,
                size: 'medium',
                placeholder: 'response xml'
              },
              httpResponseTagData: httpResponseParams,
            };
            this.authenticationConfig =authenticationConfig;
            // mqtt 相关
            this.mqttPubTopicInfo = {
              mqttPubTopicStr: {
                identify: 'Url',
                value: mqttPubTopic,
                size: 'medium',
                placeholder: '订阅 topic'
              },
              mqttPubTopicTagData: mqttPubTopicParams,
            };
            this.mqttSubTopicInfo = {
              mqttSubTopicStr: {
                identify: 'Url',
                value: mqttSubTopic,
                size: 'medium',
                placeholder: '订阅 topic'
              },
              mqttSubTopicTagData: mqttSubTopicParams,
            };
            this.mqttPubQos=mqttPubQos;
            this.mqttSubQos=mqttSubQos;
            this.mqttPayload=getStreamInfo(mqttPayload, 'payload');
            this.mqttResponse=getStreamInfo(mqttResponse, 'response');
            this.mqttPayloadInfo = {
              mqttPayloadStr: {
                identify: 'Url',
                value: mqttPayloadStr,
                size: 'medium',
                placeholder: 'payload'
              },
              mqttPayloadTagData: mqttPayloadParams,
            };
            this.mqttResponseInfo = {
              mqttResponseStr: {
                identify: 'Url',
                value: mqttResponseStr,
                size: 'medium',
                placeholder: 'response'
              },
              mqttResponseTagData: mqttResponseParams,
            };

          }else{
            console.log(256)
            this.commandForm.commandSpecial= {
              // modbus 相关设置
              funcCode: '',
                startingAddress: 0,
                nOfRegisters: 0,
                isStartFunc: false,
                startFunc: '',
                // http 相关设置
                httpMethod: commonConfig.httpMethod[0].value,
                httpContentType: commonConfig.httpContentType[0].value,
                httpContentStr: '',
                httpResponseStr: '',
              //mqtt设置
                mqttPubQos: 1,//发布qos
                mqttSubQos: 1,//订阅qos
                mqttPubTopic : '',
                mqttSubTopic : '',
                mqttPayloadType:commonConfig.mqttContentType[0].value,
                mqttResponseType:commonConfig.mqttContentType[0].value,
            }
          }
          this.reqStreamInfo.value = reqStreamStr;
          this.rspStreamInfo.value = rspStreamStr;
          this.reqExample = reqExample;
          this.rspExample = rspExample;
          this.reqTagData = reqStream;
          this.rspTagData = rspStream;
          this.relatedCommands = relatedCommands;
          this.combinedStoreKeys = combinedStoreKeys;
        }).catch(err => {
          console.log('err', err)
          this.commandFormLoading = false;
        });
      },
      genCommChanged() {
        let flatGenCommData = [];
        this.genCommData.forEach(gc => {
          flatGenCommData = _.union(flatGenCommData, gc.options || []);
        });
        this.genCommInfo = flatGenCommData.find(fgc => {
          return fgc._id === this.commandForm.generalCommand;
        }) || {};
        this.commandForm.commandName = this.genCommInfo.methodAlias || commonString.unknown;
        this.commandForm.commandType = this.genCommInfo.generalCommandType || commonString.unknown;
      },
      commandFormCancel() {
        this.$router.push({name: routerMeta.command.name});
      },
      commandFormSubmit() {
        const destTags = dealWithModelProtocol(this.reqStreamInfo.value);//编码
        const estTags = dealWithModelProtocol(this.rspStreamInfo.value);//编码 rspStreamInfo:Object
        this.$refs[this.commandFormRef].validate((valid) => {
          if (!valid) return;
          if(this.combinedStoreKeys.length>0){
            if(hasAnyEmptyProperty(this.combinedStoreKeys,'uniqueKey')){
              this.$notify({
                message: '请选择联合storeKey中的uniqueKey',
                type: 'error',
                duration: 3000,
              });
              return
            }
          }
          if(this.relatedCommands.length>0){
            if(hasAnyEmptyProperty(this.relatedCommands,'command')){
              this.$notify({
                message: '请选择关联命令中的命令',
                type: 'error',
                duration: 3000,
              });
              return
            }
          }
          for (var i = 0; i < destTags.length; i++) {

            if (destTags[i] == undefined) {
              this.$notify({
                message: '请输入正确的码流模版重新提交',
                type: 'error',
                duration: 3000,
              });
              return
            }
          }
          for (var j = 0; j < estTags.length; j++) {
            console.log(estTags[j])
            if (estTags[j] == undefined) {
              this.$notify({
                message: '请输入正确的码流模版重新提交',
                type: 'error',
                duration: 3000,
              });
              return
            }
          }
          const commandSpecial = this.commandForm.commandSpecial;
          const getHttpParams = (src = []) => {
            return src.map(s => {
              const {valueStreamInfo = {}, valueTagData = []} = s.value || {};
              return {
                key: s.key,
                valueStr: valueStreamInfo.value || '',
                valueParams: valueTagData,
              }
            }) || [];
          };
          if (commandSpecial) {
            // 根据前台界面的结构组装后台存储数据的结构

            commandSpecial.httpUrl = this.httpUrlInfo.httpUrlStr.value;
            commandSpecial.httpUrlParams = this.httpUrlInfo.httpUrlTagData;
            commandSpecial.httpHeaders = getHttpParams(this.httpHeaders);
            // http application/json 相关
            commandSpecial.httpContent = getHttpParams(this.httpContent);
            commandSpecial.httpResponse = getHttpParams(this.httpResponse);
            // http text/html 相关
            commandSpecial.httpContentStr = this.httpContentInfo.httpContentStr.value;
            commandSpecial.httpContentParams = this.httpContentInfo.httpContentTagData;
            commandSpecial.httpResponseStr = this.httpResponseInfo.httpResponseStr.value;
            commandSpecial.httpResponseParams = this.httpResponseInfo.httpResponseTagData;
            commandSpecial.authenticationConfig = this.authenticationConfig;
          }
          if(this.judgeProtocolType('MQTT')){
            this.commandForm.commandSpecial={
              mqttPayloadType: this.commandForm.commandSpecial.mqttPayloadType,
              mqttResponseType:this.commandForm.commandSpecial.mqttResponseType,
              mqttPubTopic: this.mqttPubTopicInfo.mqttPubTopicStr.value,
              mqttPubTopicParams: this.mqttPubTopicInfo.mqttPubTopicTagData,
              mqttSubTopic: this.mqttSubTopicInfo.mqttSubTopicStr.value,
              mqttSubTopicParams: this.mqttSubTopicInfo.mqttSubTopicTagData,
              mqttPubQos: this.commandForm.commandSpecial.mqttPubQos,
              mqttSubQos: this.commandForm.commandSpecial.mqttSubQos,
              mqttPayload: getHttpParams(this.mqttPayload),
              mqttResponse: getHttpParams(this.mqttResponse),
              mqttPayloadStr: this.mqttPayloadInfo.mqttPayloadStr.value,
              mqttPayloadParams: this.mqttPayloadInfo.mqttPayloadTagData,
              mqttResponseStr: this.mqttResponseInfo.mqttResponseStr.value,
              mqttResponseParams: this.mqttResponseInfo.mqttResponseTagData,

            }
          }
          const params = {
            ...this.commandForm,
            reqStreamStr: this.reqStreamInfo.value,
            reqExample: this.reqExample,
            rspStreamStr: this.rspStreamInfo.value,
            rspExample: this.rspExample,
            reqStream: this.reqTagData,
            rspStream: this.rspTagData,
            relatedCommands: this.relatedCommands,
            combinedStoreKeys: this.combinedStoreKeys,
          };
          console.log('params', params);
          if (this.$route.name === routerMeta.commandEdit.name) {
            this.commandFormLoading = true;
            API.command.commandEdit(params).then(result => {
              messageHandle({code: msgCode.EDIT_SUCCESS, title: '设备命令'});
              this.commandFormLoading = false;
              this.resetCommandForm();
              this.$router.push({name: routerMeta.command.name})
            }).catch(err => {
              console.log('err', err)
              this.commandFormLoading = false;
            });
          } else if (this.$route.name === routerMeta.commandClone.name) {
            this.commandFormLoading = true;
            delete params['_id'];
            delete params['commandNo'];
            API.command.commandAdd(params).then(result => {
              messageHandle({code: msgCode.ADD_SUCCESS, title: '设备命令'});
              this.genCommFormLoading = false;
              this.resetCommandForm();
              this.$router.push({name: routerMeta.command.name});
            }).catch(err => {
              console.log('err', err)
              this.commandFormLoading = false;
            });
          }
        });
      },
      // command map 相关
      clickCommandTag(type, tag = {}) {
        // ##param##的情况需要关联一个自定义方法
        // 命令的码流解析 和 http 设置的解析，http 的 headers 和 content 属于 Req，response 属于 Rsp
        this.selectedCommMap = {
          show: true, tag,
          type: tag.type === commonConfig.codeTagType.systemFunc ?
            'Func' : (type === 'Rsp' ? 'Rsp' : 'Req'),
          genCommInfo: this.genCommInfo
        };
      },
      funcCodeChanged() {
        this.$forceUpdate()
      }
    },
  }
</script>

<style scoped>

</style>
